from fastapi import APIRouter, HTTPException, Depends
from typing import List, Dict, Any
from api.models.schemas import (
    WorkHoursQueryRequest, 
    WorkHoursReportResponse, 
    ApiResponse,
    WorkLogDetail,
    AIServiceStatus
)
from database import get_query_helper, WorkHoursQueryHelper
from utils.logger import get_logger
from services.report_service import get_report_service, ReportConfig
from utils.config import settings

# 获取日志记录器
logger = get_logger(__name__)

router = APIRouter()


def get_query_helper_dependency() -> WorkHoursQueryHelper:
    """获取查询辅助器的依赖注入"""
    return get_query_helper()


@router.post("/reports", response_model=ApiResponse, summary="综合查询接口")
async def get_comprehensive_report(
    request: WorkHoursQueryRequest,
    query_helper: WorkHoursQueryHelper = Depends(get_query_helper_dependency)
):
    """
    综合查询接口
    
    支持按人员、部门、项目等多维度查询工时数据
    """
    try:
        logger.info(f"📊 开始综合查询: {request.dict()}")
        
        # 执行查询
        work_logs = query_helper.get_comprehensive_report(
            people_name=request.people_name,
            framework_name=request.framework_name,
            project_id=request.project_id,
            start_date=request.start_date,
            end_date=request.end_date
        )
        
        # 计算统计数据
        total_hours = sum(log.get('WorkHour', 0) for log in work_logs)
        total_records = len(work_logs)
        
        # 转换为响应模型
        work_log_details = []
        for log in work_logs:
            work_log_details.append(WorkLogDetail(**log))
        
        # 生成AI智能总结
        summary = await generate_ai_summary(work_logs, request.dict())
        
        # 构建响应
        report_response = WorkHoursReportResponse(
            summary=summary,
            total_hours=total_hours,
            total_records=total_records,
            details=work_log_details
        )
        
        logger.info(f"✅ 综合查询完成: {total_records} 条记录, {total_hours:.1f} 小时")
        
        return ApiResponse(
            code=200,
            message="查询成功",
            data=report_response.dict()
        )
        
    except Exception as e:
        logger.error(f"❌ 综合查询失败: {e}")
        raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")


def generate_basic_summary(work_logs: List[Dict[str, Any]], query_params: Dict[str, Any]) -> str:
    """生成基础总结（不调用AI服务）"""
    
    total_hours = sum(log.get('WorkHour', 0) for log in work_logs)
    total_logs = len(work_logs)
    
    # 按员工统计
    people_stats = {}
    for log in work_logs:
        name = log.get('PeopleName', '未知')
        if name not in people_stats:
            people_stats[name] = 0
        people_stats[name] += log.get('WorkHour', 0)
    
    # 按项目统计
    project_stats = {}
    for log in work_logs:
        project_name = log.get('ProjectName', '未知项目')
        if project_name not in project_stats:
            project_stats[project_name] = 0
        project_stats[project_name] += log.get('WorkHour', 0)
    
    # 生成基础总结
    summary = f"## 工时统计总结\n\n"
    
    if query_params.get('start_date') and query_params.get('end_date'):
        summary += f"**时间范围**: {query_params['start_date']} 至 {query_params['end_date']}\n\n"
    
    summary += f"**总体统计**:\n"
    summary += f"- 总工时: {total_hours:.1f} 小时\n"
    summary += f"- 总记录数: {total_logs} 条\n"
    summary += f"- 涉及员工: {len(people_stats)} 人\n"
    summary += f"- 涉及项目: {len(project_stats)} 个\n\n"
    
    if people_stats:
        summary += "**员工工时分布**:\n"
        sorted_people = sorted(people_stats.items(), key=lambda x: x[1], reverse=True)
        for name, hours in sorted_people[:5]:  # 只显示前5名
            percentage = (hours / total_hours * 100) if total_hours > 0 else 0
            summary += f"- {name}: {hours:.1f} 小时 ({percentage:.1f}%)\n"
        if len(sorted_people) > 5:
            summary += f"- ... 以及其他 {len(sorted_people) - 5} 名员工\n"
        summary += "\n"
    
    if project_stats:
        summary += "**项目工时分布**:\n"
        sorted_projects = sorted(project_stats.items(), key=lambda x: x[1], reverse=True)
        for project, hours in sorted_projects[:5]:  # 只显示前5个项目
            percentage = (hours / total_hours * 100) if total_hours > 0 else 0
            summary += f"- {project}: {hours:.1f} 小时 ({percentage:.1f}%)\n"
        if len(sorted_projects) > 5:
            summary += f"- ... 以及其他 {len(sorted_projects) - 5} 个项目\n"
        summary += "\n"
    
    summary += "**备注**: 此总结由系统自动生成。"
    
    return summary


async def generate_ai_summary(work_logs: List[Dict[str, Any]], query_params: Dict[str, Any]) -> str:
    """使用AI生成智能总结"""
    try:
        # 检查AI服务是否可用
        if not settings.ai_enabled:
            logger.warning("⚠️ AI服务未启用，使用基础总结")
            return generate_basic_summary(work_logs, query_params)
        
        # 获取AI服务实例
        ai_service = get_report_service()
        
        # 准备查询上下文信息
        context_info = {
            "query_type": "api_comprehensive_report",
            "query_params": query_params,
            "total_records": len(work_logs),
            "total_hours": sum(log.get('WorkHour', 0) for log in work_logs)
        }
        
        # 准备AI分析的数据（包含上下文）
        analysis_data = {
            "context": context_info,
            "work_logs": work_logs
        }
        
        logger.info(f"🤖 开始AI报告生成，数据量: {len(work_logs)} 条记录")
        
        # 使用AI生成报告
        config = ReportConfig(report_type="markdown")
        ai_result = ai_service.generate_report([analysis_data], config)
        
        if ai_result["success"]:
            logger.info("✅ AI报告生成成功")
            return ai_result["content"]
        else:
            logger.error(f"❌ AI报告生成失败: {ai_result.get('message', 'Unknown error')}")
            # 回退到基础总结
            return generate_basic_summary(work_logs, query_params)
            
    except Exception as e:
        logger.error(f"❌ AI报告生成异常: {e}")
        # 回退到基础总结
        return generate_basic_summary(work_logs, query_params)


# 将更具体的路由放在前面
@router.get("/reports/ai/status", response_model=ApiResponse, summary="AI服务状态检查")
async def get_ai_service_status():
    """
    检查AI服务的当前状态
    """
    try:
        from datetime import datetime
        
        # 检查AI服务配置
        ai_enabled = settings.ai_enabled
        model = getattr(settings, 'ai_model', 'deepseek-ai/DeepSeek-V3')
        
        # 尝试获取AI服务实例
        api_available = False
        try:
            if ai_enabled:
                ai_service = get_report_service()
                api_available = True
        except Exception as e:
            logger.error(f"❌ AI服务不可用: {e}")
            api_available = False
        
        # 构建状态响应
        status_response = AIServiceStatus(
            enabled=ai_enabled,
            model=model,
            api_available=api_available,
            last_check=datetime.now().isoformat()
        )
        
        return ApiResponse(
            code=200,
            message="AI服务状态查询成功",
            data=status_response.dict()
        )
        
    except Exception as e:
        logger.error(f"❌ AI服务状态检查失败: {e}")
        raise HTTPException(status_code=500, detail=f"状态检查失败: {str(e)}")
